package com.lzx.hbh_system.shiro;


import com.lzx.hbh_system.util.JWTUtil;
import com.lzx.hbh_system.util.RedisUtils;
import com.lzx.hbh_system.util.staitcParma.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * JWTFilter 自定义用来替代shiro的验证权限的自带过滤器
 *
 *
 * 代码的执行流程 preHandle -> isAccessAllowed -> isLoginAttempt -> executeLogin -> onAccessDenied 过滤器执行结束。
 */
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter{
    Boolean isVisitor = false;//默认不是游客
    /**
     * 判断是否是拒绝登录 没有登录的情况下会走此方法
     *
     * 如果isAccessAllowed方法返回True，则不会再调用onAccessDenied方法，
     * 如果isAccessAllowed方法返回Flase,则会继续调用onAccessDenied方法。
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response){
        //游客响应前端
        log.info("是否游客："+isVisitor);
        return false;//过滤链结束
    }

    /**
     * 执行登陆校验
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response){//如果这里报了异常 isAccessAllowed 会catch到异常
        //初始化一个刷新token类
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");
        //判断是否需要刷新token，传入请求携带的需要验证的token
        String newtoken = ReflushToken.getAndCheckToken(token);
        // 将请求中的token放入我们自定义的JWTToken校验类中，存放用于Shiro校验权限
        JWTToken jwtToken = new JWTToken(newtoken);
        // 提交给自定义的JWTRealm进行登入，如果错误它会抛出异常并被捕获
        getSubject(request,response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     * 判断是否登陆登陆
     * 检查请求头是否存在token，
     * 存在 则直接进行登陆验证,
     * 不存在 也设置return true 可进行游客访问操作，不检查token
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request,response)){
            try {
                executeLogin(request,response);
            } catch (Exception e) {
                System.out.println("executeLogin异常信息："+e.getMessage());
                if(e.getMessage().equals("LockedAccountException")){

                    log.error(ResultEnum.USER_LOCKED.getMsg());
                    responseError(request,response,ResultEnum.USER_LOCKED.getCode(), ResultEnum.USER_LOCKED.getMsg());
                    return false;
                }
                else if(e.getMessage().equals("SSEServiceError")){
                    log.error(ResultEnum.SYSTEM_SSESERVICE_ERROR.getMsg());
                    responseError(request,response, ResultEnum.SYSTEM_SSESERVICE_ERROR.getCode(),ResultEnum.SYSTEM_SSESERVICE_ERROR.getMsg());
                    return false;
                }
                else if (e.getMessage().equals("TokenExpiredException")){

                    log.error(ResultEnum.TOKEN_OUT_OF_DATE.getMsg());
                    responseError(request,response, ResultEnum.TOKEN_OUT_OF_DATE.getCode(),ResultEnum.TOKEN_OUT_OF_DATE.getMsg());
                    return false;
                }
                else if(e.getMessage().equals("UserLoginStatusTimeOutException")){

                    log.error(ResultEnum.ACCESS_LOGIN_TIME_OUT.getMsg());
                    responseError(request,response,ResultEnum.ACCESS_LOGIN_TIME_OUT.getCode(), ResultEnum.ACCESS_LOGIN_TIME_OUT.getMsg());
                    return false;
                }
                else if(e.getMessage().equals("CredentialsException")){

                    log.error(ResultEnum.TOKEN_NOT_MATCHE.getMsg());
                    responseError(request,response,ResultEnum.TOKEN_NOT_MATCHE.getCode(), ResultEnum.TOKEN_NOT_MATCHE.getMsg());
                    return false;
                }else if(e.getMessage().equals("LOGINOUTEXECEPTION")){
                    log.error(ResultEnum.ACCESS_ERROR.getMsg());
                    responseError(request,response,ResultEnum.ACCESS_ERROR.getCode(), ResultEnum.ACCESS_ERROR.getMsg());

                }
            }
            return true;
        }else{
            log.error(ResultEnum.USER_UNLOGIN.getMsg());
            isVisitor = true;//当前游客访问
        }
        return true;
//        return false;
        //如果请求头不存在 token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true - 具体效果还不太清楚
        //现在方案-return false，不登陆，然后会执行onAccessDenind 返回前端说明游客登陆
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        return super.onLoginFailure(token, e, request, response);
    }

    /**
     * 判断用户是否想要登陆
     * 检查请求头是否存在token
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");
        return token != null;//token 不为空就是true
    }

    /**
     * 跨域支持
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 登陆验证异常响应处理方法
     * @param response
     * @param code
     * @param msg
     */
    public void responseError(ServletRequest request,ServletResponse response,int code,String msg){
        try {
            request.setCharacterEncoding("utf-8");
            String uri = "/error/" + code + "/" + msg;
            request.getRequestDispatcher(uri).forward(request, response);
        } catch (ServletException ex) {
            log.error(ex.getMessage());
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
    }
    /**
     * 转发至Sse服务方法
     */
    public void SseService(ServletRequest request,ServletResponse response,String username,String msg){
        try {
            request.setCharacterEncoding("utf-8");
            String uri = "/sse/sendOne/" + username + "/" + msg;
            request.getRequestDispatcher(uri).forward(request, response);
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
